import 'package:flutter/widgets.dart';
import 'package:library_base/entities/buyer_entity.dart';
import 'package:library_base/provider/base_controller.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:azlistview/azlistview.dart';

class ChooseBuyerController extends BaseController {
  RxList<BuyerEntity> cityList = <BuyerEntity>[].obs;

  RxList<BuyerEntity> cityListWithKeyWord = <BuyerEntity>[].obs;

  Rxn<BuyerEntity?> suppliersEntity = Rxn<BuyerEntity?>();

  int selectedPosition = -1;

  int selectedIfWordIsEmptyPosition = -1;

  Rx<String> keyWord = ''.obs;

  Rx<bool> isAction = false.obs;

  final TextEditingController keyWorkSearchController = TextEditingController();

  late void Function(BuyerEntity) callback;

  @override
  void onCreate() {
    var argumentMap = Get.arguments as Map<String, dynamic>;

    cityList.value = argumentMap['Buyer'] as List<BuyerEntity>;

    suppliersEntity.value = argumentMap['SelectedBuyer'] as BuyerEntity?;
    callback = argumentMap['callback'];

    _handleList(cityList);

    if (suppliersEntity.value != null) {
      var selectedBuyerEntity =
          cityList.firstWhere((element) => element.userId == suppliersEntity.value!.userId);
      selectedBuyerEntity.isSelect = true;
      suppliersEntity.value = selectedBuyerEntity;
      selectedPosition = cityList.indexOf(selectedBuyerEntity);
    }
  }

  void changeBuyer() {
    Get.back();
    callback.call(suppliersEntity.value!);
  }

  void _handleList(List<BuyerEntity> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].nickname);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }

    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(list);

    for (var element in cityList) {
      if (suppliersEntity.value == element) {
        element.isSelect = true;
      }
    }
    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(cityList);

    update();
  }
}
